<template>
  <div class="yard-list-wrapper" style="display: flex; flex-direction: column; height: 100%">
    <div v-if="title" class="block-title" style="flex: none">{{ title }}</div>
    <a-input-search
      v-if="inputVisible"
      v-model:value="houseName"
      class="yard-list-search"
      placeholder="请输入名称"
      allow-clear
      style="flex: none"
      @change="change"
    />
    <div
      v-if="renderList && renderList.length"
      class="yard-list-scroll"
      style="flex: auto; height: auto; min-height: 0; overflow: hidden auto"
    >
      <div
        v-for="(item, index) of renderList"
        :key="item[fields.key] || index"
        :class="{ active: activeId === item[fields.value] }"
        class="yard-list-scroll-item"
      >
        <div class="item-name" @click="click(item)">{{ item[fields.label] }}</div>
        <div v-if="detailsVisible" class="item-details" @click="details(item)">详情</div>
      </div>
    </div>
    <empty v-else size="80px" />
  </div>
</template>

<script>
import debounce from 'lodash-es/debounce.js';
import filter from 'lodash-es/filter.js';
import get from 'lodash-es/get.js';
import { dialog } from '@gis/lib/components/antd-dialog';
import { handleCommonRes } from '@gis/lib/utils/resolver.js';
import Empty from '@gis/lib/components/Empty/index.vue';
import areaCodeMixin from '@gis/lib/mixins/areaCodeMixin.js';

import { getYardSelectList } from '@gis/lib/api/index.js';

export default {
  name: 'yard-list',
  emits: ['update:modelValue', 'change'],
  components: { Empty },
  mixins: [areaCodeMixin],
  props: {
    title: { type: String, default: '小区名称' },
    api: { type: Function, default: undefined },
    modelValue: { type: [String, Number], default: undefined },
    replaceFields: { type: Object, default: () => ({}) },
    dataSource: { type: Array, default: () => [] },
    autoSelectFirstData: { type: Boolean, default: true },
    inputVisible: { type: Boolean, default: true },
    detailsVisible: { type: Boolean, default: true },
  },
  data() {
    return {
      houseName: '',
      activeId: null,
      dataList: [],
      renderList: [],
    };
  },
  computed: {
    fields() {
      return Object.assign({ label: 'yard_name', value: 'key', key: 'key' }, this.replaceFields);
    },
  },
  mounted() {
    this.$watch(
      () => this.dataSource,
      () => {
        if (this.dataSource !== undefined) {
          this.dataList = this.dataSource;
          this.renderList = this.dataList;
        }
      },
      { immediate: true }
    );
    this.$watch(
      () => this.modelValue,
      () => {
        if (this.activeId !== this.modelValue) {
          this.activeId = this.modelValue;
          setTimeout(() => {
            const scrollEl = this.$el.querySelector('.yard-list-scroll');
            const el = this.$el.querySelector('.yard-list-scroll-item.active');
            if (scrollEl && el) {
              scrollEl.scrollTo({
                top: el.offsetTop - el.offsetHeight * 3,
                left: 0,
                behavior: 'smooth',
              });
            }
          }, 1000);
        }
      },
      { immediate: true }
    );
  },
  methods: {
    change: debounce(function () {
      const str = String(this.houseName).trim() || '';
      if (!str) {
        this.renderList = this.dataList;
        return;
      }
      this.renderList = filter(this.dataList, (item) => {
        const name = get(item, this.fields.label) || '';
        return name.indexOf(str) >= 0;
      });
    }, 500),
    async getDataAsync(params) {
      if (this.inputVisible) {
        if (!params) {
          params = Object.assign({}, this.apiParams);
        }
        params['yard_name'] = this.houseName;
      }
      if (this.dataSource && this.dataSource.length) {
        this.dataList = this.dataSource;
        this.renderList = this.dataSource;
      } else {
        const api = typeof this.api === 'function' ? this.api : this.getDataList;
        const list = (await api(params).catch(() => [])) || [];
        this.dataList = list;
        this.renderList = list;
      }
      if (!this.modelValue && this.autoSelectFirstData && this.dataList.length) {
        this.click(this.dataList[0]);
      }
    },
    async getDataList(params) {
      const list = await handleCommonRes(getYardSelectList(params));
      return list.map((item) => {
        return { ...item, key: item.yard_id };
      });
    },
    click(data = {}) {
      this.activeId = data[this.fields.value];
      this.$emit('update:modelValue', this.activeId);
      this.$emit('change', this.activeId);
    },
    details(data = {}) {
      dialog({
        content: () => import('./yard-details/index.vue'),
        contentProps: { data },
        dialogProps: {
          title: '小区详情',
          width: 'large',
          height: 'fixed',
          footer: null,
          bodyStyle: { padding: 0 },
        },
      });
    },
  },
};
</script>

<style scoped lang="less">
.yard-list-wrapper {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 0 20px;

  .block-title {
    flex: none;
    font-size: 18px;
    font-weight: bold;
    color: #ffffff;
    line-height: 40px;
  }
  .yard-list-search {
    flex: none;
    width: 100%;
    margin: 0 0 14px;
    /deep/ .ant-input {
      color: #ffffff;
    }

    /deep/ .ant-input-prefix:after {
      content: '';
      display: inline-block;
      width: 0;
      height: 18px;
      margin: 0 9px;
      border-right: 1px solid #5e676f;
    }

    &.ant-input-affix-wrapper /deep/ .ant-input:not(:first-child) {
      padding-left: 45px;
    }
  }

  .yard-list-scroll {
    flex: auto;
    height: auto;
    min-height: 0;
    overflow: hidden auto;
    margin: 0 -20px;
    padding: 0 20px;

    .yard-list-scroll-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 0;

      &.active {
        background: url('../assets/menu_pic_check_t.png') center center no-repeat;
        background-size: 100% 100%;
      }

      .item-name {
        flex: auto;
        max-width: 100%;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        text-align: left;
        font-size: 14px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #ffffff;
        cursor: pointer;
      }

      .item-details {
        flex: none;
        width: 3em;
        text-align: right;
        font-size: 14px;
        font-family: Microsoft YaHei;
        font-weight: 400;
        color: #6cccc3;
        cursor: pointer;
      }
    }
  }
}
</style>
